﻿// MakingWaves: UploadControl

var openWaves;
if (!openWaves) {
    openWaves = {};
} else if (typeof openWaves !== "object") {
    throw new Error("openWaves already exists and is not an object");
}

openWaves.UploadControl = function (settings) {
    var self = this;

    this.queueId = settings.queueId;
    this.uploadOptions = settings;

    this.onUploadProgress = function (file) {
        $('#' + file.id + " b").html(file.percent + "%");
    };

    this.onFileUploaded = function (file) {
        $('#' + file.id + " b").html("100%");
    };

    this.onUploadComplete = function (files) {

    };

    this.onStateChanged = function () {

    };

    this.onFilesAdded = function (files) {
        if (self.queueId !== null && self.queueId.length > 0) {
            $.each(files, function (i, file) {
                $("#" + self.queueId).append(
                        '<div id="' + file.id + '">' +
                            file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
                                '</div>');
            });
        }
    };

    this.remove = function (file) {
        self.upload.removeFile(file);
    };

    this.initialize = function () {
        self.upload = new plupload.Uploader(self.uploadOptions);
        self.upload.init();

        self.upload.bind('FilesAdded', function (up, files) {
            self.onFilesAdded(files);

            up.refresh();
            if (self.upload.state === plupload.STOPPED) {
                self.upload.start();
            }
        });

        self.upload.bind('UploadProgress', function (up, file) {
            self.onUploadProgress(file);
        });

        self.upload.bind('StateChanged', function () {
            self.onStateChanged();
        });

        self.upload.bind('UploadComplete', function (up, files) {
            self.onUploadComplete(files);

            if (self.uploadOptions.autoPostBack == true) {
                eval(self.uploadOptions.autoPostBackScript);
            }
        });

        self.upload.bind('FileUploaded', function (up, file, response) {
            var fileNamesArray = new Array();
            $.each(self.upload.files, function (i, f) {
                var fileInfo = new Object();
                fileInfo.FileName = f.name;
                fileInfo.TempFileName = response.response;
                fileInfo.Size = f.size;
                fileNamesArray[i++] = fileInfo;
            });

            self.onFileUploaded(file);
            var val = JSON.stringify(fileNamesArray);
            $('#' + self.uploadOptions.stateContainer).val(val);
        });
    };
};